const db=wx.cloud.database()
const _=db.command
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchKey: '',
    novels:'',
    searchlist:'',
    appear:'',
    curNum:0
  },
  // 获取搜索框数据
  searchKey(e){
    this.setData({searchKey:e.detail.value})
  },
  // 取消
  cancel(){
    this.setData({
      searchKey: '',
      novels:'',
      curNum:0
    })
    let sear = wx.getStorageSync('search')
    this.setData({searchlist:sear.reverse()})
    if(sear.length>0){
      this.setData({appear:'ture'})
    }
  },
  // 数组去重
  arrSet:function(value,arr) {
    let obj = {}
    let res = arr.reduce((pre, cur) => {
        if (!obj[cur[value]]) {
            obj[cur[value]] = true
            pre.push(cur)
        }
        return pre
    }, [])
    return res
  },
  // 搜索
  search(){
    let that=this
    let searchKey = this.data.searchKey
    wx.cloud.callFunction({
      name:"search",
      data: {
        searchKey: searchKey,
      },
    })
    .then(res=>{
      console.log('s',res)
      this.setData({novels:res.result.list})
      console.log('sss',this.data.novels)
      let action ={}
      let search = wx.getStorageSync('search')
      action.name = searchKey
      search.push(action)
      let search0 = this.arrSet('name',search)
      wx.setStorageSync( 'search', search0)
      let search1 = wx.getStorageSync('search')
      that.setData({searchlist:search1.reverse()})
      })
      this.setData({curNum:1})
  },
   //跳转小说列表
   goNovel(e){
    wx.navigateTo({
      url: '../novels/novels?id='+e.currentTarget.dataset.id,
    })
  },
  onLoad: function (){
    this.searched()
  },
  // 搜索历史
  searched(){
    let sear = wx.getStorageSync('search')
    this.setData({searchlist:sear.reverse()})
    if(sear.length>0){
      this.setData({appear:'ture'})
    }
  },
  // 清空搜索历史
  cancelplus(){
    this.setData({
      searchlist:'',
      appear:''
    })
    wx.setStorageSync('search', [])
  },
  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh() {
    this.searched()
    wx.stopPullDownRefresh()
  },

  // 页面上拉触底事件的处理函数
  onReachBottom() {
    wx.showToast({
      icon: 'none',
      title: '没有更多数据了',
    })
  },

})